import redis
from src.config.redis_config import RedisConfig as RedisConfig


class RedisHandler:
    # 连接池
    Connection_Pool = None
    # redis客户端
    Client = None
    # 默认过期时间，单位：秒
    Default_Expire_Time = 60 * 60 * 6
    # Expire_Time = 60

    @staticmethod
    def create_client():
        """
        连接redis，返回client对象
        :return:
        """
        RedisHandler.Connection_Pool = redis.ConnectionPool(host=RedisConfig.IP, port=RedisConfig.PORT,
                                                            db=RedisConfig.DATABASE)
        RedisHandler.Client = redis.Redis(connection_pool=RedisHandler.Connection_Pool)

    @staticmethod
    def set_with_default_expire_time(key, value):
        """
        设置key-value对，同时设置默认的过期时间
        :param key:
        :param value:
        :return:
        """
        RedisHandler.Client.set(key, value)
        RedisHandler.Client.expire(key, RedisHandler.Default_Expire_Time)

    @staticmethod
    def set_forever(key, value):
        """
        设置key-value对，永不过期
        :param key:
        :param value:
        :return:
        """
        RedisHandler.Client.set(key, value)

    @staticmethod
    def set_with_expire_time(key, value, expire_time):
        """
        设置key-value对，同时设置过期时间
        :param key:
        :param value:
        :param expire_time:
        :return:
        """
        RedisHandler.Client.set(key, value)
        RedisHandler.Client.expire(key, expire_time)

    @staticmethod
    def get(key):
        """
        根据key，返回value
        :param key:
        :return:
        """
        return RedisHandler.Client.get(key)

    @staticmethod
    def close():
        """
        关闭连接池。关闭了从该连接池打开的所有连接。但是，它不会阻止打开新连接。
        :return:
        """
        RedisHandler.Connection_Pool.disconnect()
